﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BulletOnRailsControllers.Controllers;
using System.IO;

namespace BulletOnRailsControllers.Controllers
{
    public class CacheHelper
    {
        public static bool IsViewCached(int param_id, string view_path)
        {
            return File.Exists(ConvertViewPathToCacheFilePath(param_id,
                view_path));
        }

        public static string CreateCachedView(object param_id, string view_path, string master_path,
            Controller controller, object view_model)
        {

            controller.ViewData.Model = view_model;
            string cache_view_contents = RenderToFileHelper.RenderViewToString(controller.ControllerContext,
                view_path, master_path, controller.ViewData, controller.TempData);

            FileInfo cached_view_file = new FileInfo(ConvertViewPathToCacheFilePath(param_id,
                view_path));
            StreamWriter Tex = cached_view_file.CreateText();
            Tex.Write(cache_view_contents);
            Tex.Close();

            return cache_view_contents;
        }

        public static string GetCachedView(object param_id, string view_path)
        {
            FileInfo cached_view_file = new FileInfo(ConvertViewPathToCacheFilePath(param_id,
                         view_path));
            StreamReader Tex = cached_view_file.OpenText();
            string cache_view_contents = Tex.ReadToEnd();
            Tex.Close();

            return cache_view_contents;
        }
        protected static string ConvertViewPathToCacheFilePath(object param_id, string view_path)
        {
            return HttpContext.Current.Server.MapPath(view_path.ToUpper().Replace("VIEWS", "Cache")) +
                 ".cache" + param_id.ToString();
        }
    }
}
